<?php

namespace App\Http\Controllers\Wechat;

use App\Models\StoreOrders;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use Session , Cookie , Config , Log , Validator;

use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order as WechatOrder;

use App\Models\Order;
use App\Models\OrderInfo;
use App\Models\User;
use App\Models\WxPay;

use App\Libs\Jpush;

class PayController extends Controller
{

    private $wechat;
    public function __construct(){

        $this->wechat = new Application(Config::get('wechat'));

    }

    public function getPayData(Request $request){
        $validation = Validator::make($request->all(), [
            'oid'            => 'required',
        ]);
        if($validation->fails()){
            $error = $validation->errors()->all();
            return response()->json(['code' => -1 , 'msg' => $error[0]]);
        }

        $oid = $request->get('oid');

        $orderInfo = Order::where('status' , 1)->where('id' , $oid)->first();

        Log::debug($oid);

        if(!$orderInfo){
            return response()->json(['code' => -2 , 'msg' => "订单信息不存在"]);
        }

        global $uid;

        $userInfo = User::where('id' , $uid)->whereNull('deleted_at')->first();

        if(!$userInfo){
            return response()->json(['code' => -3 , 'msg' => "用户信息不存在"]);
        }

        $attributes['trade_type']       = 'JSAPI';
        $attributes['body']             = $orderInfo->order_num;
        $attributes['detail']           = $orderInfo->order_num;
        $attributes['out_trade_no']     = md5($orderInfo->order_num);
        $attributes['fee_type']         = 1;
        $attributes['attach']           = $orderInfo->id;
//        $attributes['total_fee']        = $orderInfo->pay_total;
        $attributes['total_fee']        = 1;
        $attributes['notify_url']       = Config::get('wechat.notify_url');
        $attributes['openid']           = $userInfo->wx_openid;

        $app = new Application(Config::get('wechat'));
        $payment = $app->payment;

        $order = new WechatOrder($attributes);

        $result = $payment->prepare($order);

        Log::debug(Config::get('wechat'));
        Log::debug($order);

        if ($result->return_code == 'SUCCESS' && $result->return_msg == 'OK'){

            $prepayId = $result->prepay_id;
            $json = $payment->configForPayment($prepayId);
            $json = json_decode($json);

            Log::info(json_encode($json));

            unset($attributes['notify_url']);
            $attributes['oid'] = $oid;

            $isCreate = false;
            if(WxPay::where('oid' , $oid)->first()){
                $isCreate = WxPay::where('oid' , $oid)->update($attributes);
            }else {
                $isCreate = WxPay::create($attributes);
            }

            if ($isCreate) {
                return response()->json(['code' => 0, 'data' => $json]);
            }else{
                return response()->json(['code' => -5 , 'msg' => "创建支付信息失败,请重试"]);
            }
        }else{
            Log::error($request);
            return response()->json(['code' => -4 , 'msg' => "请求失败"]);
        }

    }



    /**
     * [setPayData description]
     * @param [type] $app [description]
     * 生成订单数据
     */
    public function payNotify(){

        $app = new Application(Config::get('wechat'));

        $response = $app->payment->handleNotify(function($notify, $successful){

            $outTradeNo = $notify->out_trade_no;

            $wxpayData = WxPay::where('out_trade_no' , $outTradeNo)->first();

            if(!$wxpayData){
                return 'Order not exist.';
            }

            $order = Order::where('id' , $wxpayData->oid)->first();

            Log::debug($order);
            //已经支付了
            if($order->pay_time){
                return true;
            }

            if($successful){

                $orderModel = new Order;
                //更新支付时间和订单状态
                $payResult = $orderModel->pay($order->id , ($notify->total_fee / 100) , $notify->time_end , $notify->transaction_id , '');
                if(!$payResult){
                    return '服务器处理失败';
                }else{

                    $orderInfo = OrderInfo::where('o_id' , $order->id)->get();
                    $gname = '';
                    foreach ($orderInfo as $oi){
                        $gname .= $oi->name .' ';
                    }

                    //给用户发微信通知
                    $notice = $this->wechat->notice;
                    $userId = $wxpayData->openid;
                    $templateId = '--bcDU0TkTFx-W17SlyVhTcLW9-LUADOMdq0v35IdIw';
                    $url = Config::get('app.url').'/order/info/'.$wxpayData->oid;
                    $data = array(
                        "first"         => "您的订单交易完成！我们将尽快安排发货,确保及时送到您手上",
                        "keyword1"      => $gname,
                        "keyword2"      => $order->order_num,
                        "keyword3"      => priceIntToFloat($order->pay_total),
                        "keyword4"      => $notify->time_end,
                        "remark"        => "欢迎再次购买"
                    );
                    $result = $notice->uses($templateId)->withUrl($url)->andData($data)->andReceiver($userId)->send();
                    Log::debug($result);

                    //给店铺发通知
                    $storeInfo = StoreOrders::where('o_id' , $order->id)->first();
                    $jpush = new Jpush('commercial');

                    $content    = "果小哥有新订单啦,请及时处理";
                    $title      = "果小哥";
                    $platform   = 'all';
                    $alias      = "$storeInfo->s_id";
                    $tag        = array();
                    $sound      = 'default';
                    $type       = "new";

                    try {
                        $jpush->push($content, $title, $platform, $alias, $tag, $sound, $type);
                    }catch (\Exception $e){
                        \Log::debug($e);
                    }
                    return true;
                }
            }
            return true;

        });

        return $response;
    }

    public function push(){
        //给店铺发通知
        $jpush = new Jpush('commercial');

        $content    = "果小哥有新订单啦,请及时处理";
        $title      = "果小哥";
        $platform   = 'all';
        $alias      = '12';
        $tag        = array();
        $sound      = 'default';
        $type       = "new";

        Log::debug($jpush->push($content , $title , $platform , $alias , $tag , $sound , $type));

        return response()->json(['code' => 0]);
    }

    public function refund(Request $request)
    {
        $validation = Validator::make($request->all(), [
            'o_id' => 'required',
        ], [
            'o_id.required' => '没有订单',
        ]);
        if ($validation->fails()) {
            $error = $validation->errors()->all();
            return response()->json(['code' => -1, 'msg' => $error[0]]);
        }

        global $uid;
        $oId = $request->get('o_id');

        $order = Order::where('u_id', $uid)->where('id', $oId)->first();

        if (!$order) {
            return response()->json(['code' => -2, 'msg' => '订单不存在']);
        }

        if ($order->status == 2) {

            $wxPayInfo = WxPay::where('o_id', $oId)->first();
            if (!$wxPayInfo) {
                return response()->json(['code' => -3, 'msg' => '订单不存在']);
            }

            $app = new Application(Config::get('wechat'));
            $refundNo = md5($order->order_num . 'refund');
            $result = $app->payment->refundByTransactionId($wxPayInfo->transaction_id, $refundNo, 100);

            if ($request->return_code == 'SUCCESS') {
                if (WxPay::where('o_id', $oId)->update(['refund_no' => $refundNo]) === false) {
                    \Log::error('退款更新数据库失败----order-id---' . $oId);
                }
                return response()->json(['code' => 0, 'msg' => '申请成功']);
            } else {
                \Log::error($result);
                return response()->json(['code' => -4, 'msg' => '申请失败']);
            }
        }elseif($order->status == 1) {
            if(Order::where('u_id', $uid)->where('id', $oId)->update(['status' => 6]) === false){
                return response()->json(['code' => -6, 'msg' => '取消失败']);
            }else{
                return response()->json(['code' => 0, 'msg' => '取消成功']);
            }
        }else{
            return response()->json(['code' => -5, 'msg' => '订单不可取消']);
        }

    }

}